/**
 * 页面框架
 * var 1.0
 */
window.initStats = 0;
(function ($, owner) {
    /**
     * 初始化自动绑定
     */
    owner.init = function () {
        //处理绑定组件
        if (window['initStats']) {
            return false;
        }
        $("[data-dux]").each(function () {
            var data = $(this).data(),
                name = data['dux'],
                names = name.split('-', 2);
            if (window[names[0]][names[1]] && typeof (window[names[0]][names[1]]) == "function") {
                window[names[0]][names[1]](this, data);
            } else {
                app.debug(names[0] + '组件中不存在' + names[1] + '方法!');
            }

        });
        if (window['windowAfter'] != undefined && window['windowAfter'] != '') {
            window['windowAfter']();
        }
        window.initStats = 1;
    };

    /**
     * 自定义绑定
     */
    owner.bind = function ($el) {
        $($el).find("[data-dux]").each(function () {
            var data = $(this).data(),
                name = data['dux'],
                names = name.split('-', 2);
            window[names[0]][names[1]](this, data);
        });
    };

    /**
     * 自定义绑定插件
     */
    owner.plugins = function ($el, data) {
        Do(data['bind'], function () {
            var fun = new Function('$el', '$($el).' + data['bind'] + '(' + data["params"] + ');');
            fun($el);
        });
    }
}(jQuery, window.dux = {}));


(function ($, owner) {

    var pre = window;
    if ($('body', window.parent.document).length > 0) {
        pre = parent;
    }
    var dialogObj = new Array();
    /**
     * 加载提示
     * @param msg
     */
    owner.loading = function (msg, status) {
        var defaultConfig = {
            msg: '加载中...',
            status: true
        };
        var config = $.extend(defaultConfig, {
            msg: msg,
            status: status
        });
        var html = '<div class="dux-loading"><div class="loading-mask"></div><div class="loading-body"><div class="loading-icon"></div><div class="loading-msg">' + config.msg + '</div></div></div>';
        if (config.status) {
            if ($('.dux-loading').length) {
                return false;
            }
            $(html).appendTo('body');
        } else {
            setTimeout(function () {
                $('.dux-loading').remove();
            }, 100);
        }

    };
    /**
     * 消息提示
     * @param msg
     */
    owner.msg = function (msg, time) {
        var defaultConfig = {
            msg: '加载中',
            time: 3
        };
        var config = $.extend(defaultConfig, {
            msg: msg,
            time: time
        });
        var html = '<div class="dux-msg-layout"><div class="dux-msg"><div class="text">' + config.msg + '</div></div></div>';
        if ($('.dux-msg-layout').length) {
            $('.dux-msg-layout').remove();
        }
        $(html).appendTo('body');
        setTimeout(function () {
            $('.dux-msg-layout').remove();
        }, config.time * 1000);

    };
    /**
     * AJAX确认
     * @param $el
     */
    owner.ajaxConfirm = function ($el) {
        $($el).click(function () {
            var data = $(this).data();
            owner.confirm({
                title: data.title,
                callback: [function () {
                    app.ajax({
                        url: data.url,
                        type: 'post',
                        data: data.params,
                        success: function (msg, url) {
                            var callback = data.callback;
                            if (callback != undefined && callback != '') {
                                window[callback](msg, url);
                            } else {
                                location.reload();
                            }
                        },
                        error: function (msg, url) {
                            app.error(msg, url);
                        }
                    });
                }]
            });
        });
    };

    /**
     * 询问窗口
     * @param config
     */
    owner.confirm = function (config) {
        var defaultConfig = {
            title: '询问',
            btn: ['确认', '取消'],
            callback: []
        };
        config = $.extend(defaultConfig, config);
        UIkit.modal.confirm(config.title, {
            labels: {
                ok: config.btn[0],
                cancel: config.btn[1]
            }
        }).then(config.callback[0], config.callback[1]);

    };


    /**
     * 打开窗口
     * @param $el
     * @param config
     */
    owner.open = function ($el, config) {
        var defaultConfig = {
            width: '',
            height: '400px'
        };
        config = $.extend(defaultConfig, config);

        var open = function (url, height) {
            dialogObj.push(UIkit.modal.dialog('<button class="uk-modal-close-default" type="button" uk-close></button>\n' +
                '        <div class="uk-modal-header">\n' +
                '            <h2 class="uk-modal-title">' + config.title + '</h2>\n' +
                '        </div>' +
                '<iframe src="' + url + '" width="100%" height="' + height + '" frameborder="0"></iframe>', {
                    class: config.width ? 'uk-modal-container' : ''
                }
            ));
        };

        if ($el) {
            $($el).on('click', function () {
                open(config.url, config.height);
            });
        } else {
            open(config.url, config.height);
        }
    };

    /**
     * 关闭窗口
     */
    owner.close = function (type) {
        for (var i in dialogObj) {
            dialogObj[i].hide();
        }
        $('.dux-msg-layout').remove();
    };

    /**
     * 确认对话框
     * @param config
     */
    owner.alert = function (config) {
        UIkit.modal.alert(config.title, {
            labels: {
                ok: config.btn ? config.btn : '确认'
            }
        }).then(function () {
            if (typeof config.callback == 'function') {
                config.callback();
            }
        });
    };

}(jQuery, window.dialog = {}));


/**
 * 表单操作
 */
(function ($, owner) {
    /**
     * 绑定AJAX提交
     */
    owner.bind = function ($el, config) {
        var defaultConfig = {
            advanced: true
        };
        config = $.extend(defaultConfig, config);
        Do('form', function () {
            var profiler = function (data) {
                if (!debug) {
                    return false;
                }
                if (!data) {
                    return false;
                }
            };
            var options = {
                dataType: 'json',
                beforeSubmit: function () {
                    $($el).find("button[type=submit]").prepend('<i class="fa fa-circle-o-notch fa-spin"></i> ');
                    $($el).find("button").attr("disabled", true);

                },
                uploadProgress: function (event, position, total, percentComplete) {},
                complete: function () {
                    $($el).find("button").attr("disabled", false);
                    $($el).find("button[type=submit]").find('i:first-child').remove();

                },
                success: function (json) {
                    var msg = json.message;
                    var url = json.url;

                    profiler(json);

                    //成功回调
                    if (typeof config.callback === 'function') {
                        config.callback(msg, url);
                        return;
                    }
                    if (typeof config.callback === 'string') {
                        window[config.callback](msg, url);
                        return;
                    }
                    //执行弹窗
                    if (url) {
                        if (config.advanced) {
                            dialog.confirm({
                                title: msg,
                                btn: ['返回', '继续'],
                                callback: [function () {
                                    window.location.href = url;
                                }, function () {
                                    location.reload();
                                }]
                            });
                        } else {
                            dialog.alert({
                                title: msg,
                                callback: function () {
                                    window.location.href = url;
                                }
                            });
                        }
                    } else {

                        if (config.advanced) {
                            notify.success({
                                content: msg
                            });
                        } else {
                            dialog.alert({
                                title: msg,
                                callback: function () {
                                    location.reload();
                                }
                            });
                        }
                    }
                },
                error: function (e) {
                    var json = eval('(' + e.responseText + ')');
                    var msg = json.message;
                    var url = json.url;
                    profiler(json);
                    if (config.advanced) {
                        notify.error({
                            content: msg
                        });
                    } else {
                        app.error(msg, url);
                    }
                }
            };
            $($el).validator({
                H5validation: false,
                validateOnSubmit: true,
                onValid: function (validity) {
                    $(validity.field).closest('.uk-form-group').find('.uk-form-alert').remove();
                },
                markValid: function (validity) {
                    var options = this.options;
                    var $field = $(validity.field);
                    var $parent = $field.closest('.uk-form-group');
                    $field.removeClass(options.inValidClass);
                    $parent.removeClass('uk-form-group-error');
                    options.onValid.call(this, validity);
                },
                onInValid: function (validity) {
                    var $field = $(validity.field);
                    var msg = $field.data('validationMessage') || this.getValidationMessage(validity);
                    if (config.advanced) {
                        var $group = $field.parent();
                        if ($group.hasClass('uk-input-group')) {
                            $group = $field.parent().parent();
                        }
                        var $alert = $group.find('.uk-form-alert');
                        if (!$alert.length) {
                            $alert = $('<div class="uk-form-alert uk-text-danger"></div>').hide().appendTo($group);
                        }
                        $alert.html(msg).show();
                    } else {
                        dialog.msg(msg);
                    }
                },
                submit: function () {
                    var formValidity = this.isFormValid();
                    //clearSave
                    if (window['duxEditor']) {
                        for (var i in window['duxEditor']) {
                            window['duxEditor'][i].sync();
                            window['duxEditor'][i].clearSave();
                        }
                    }

                    if (formValidity) {
                        if (typeof CKEDITOR == 'object') {
                            for (var instanceName in CKEDITOR.instances) {
                                CKEDITOR.instances[instanceName].updateElement();
                            }
                        }
                        $($el).ajaxSubmit(options);
                    }
                    return false;
                }
            });
            $($el).find("button").attr("disabled", false);
        });
    };


    /**
     * 时间日期
     * @param $el
     * @param config
     */
    owner.date = function ($el, config) {
        Do(mobile ? 'date_mobile' : 'date', function () {
            if (!mobile) {
                var defaultConfig = {
                    elem: $el,
                };
                config = $.extend(defaultConfig, config);
                laydate.render(config);
            } else {
                var defaultConfig = {
                    input: $($el).attr('id'),
                    time: false,
                };
                config = $.extend(defaultConfig, config);
                config.timeSelector = config.time;
                new Jcalendar(config);
            }
        });

    };

    /**
     * 地区选择
     * @param $el
     * @param config
     */
    owner.location = function ($el, config) {
        var defaultConfig = {};
        config = $.extend(defaultConfig, config);
        Do(mobile ? 'distpicker_mobile' : 'distpicker', function () {
            if (!mobile) {
                $($el).distpicker(config);
            } else {
                new MultiPicker({
                    input: $($el).attr('id'), //点击触发插件的input框的id
                    container: $($el).attr('id') + '_layout', //插件插入的容器id
                    jsonData: $city,
                    success: function (arr) {
                        var values = [];
                        for (var i in arr) {
                            values.push(arr[i].value);
                        }
                        $('[name="' + $($el).data('province') + '"]').val(values[0]);
                        $('[name="' + $($el).data('city') + '"]').val(values[1]);
                        $('[name="' + $($el).data('district') + '"]').val(values[2]);
                        $($el).val(values.join(' '));
                    }
                });
            }
        });
    };

    /**
     * 编辑器
     * @param $el
     * @param config
     */
    owner.editor = function ($el, config) {
        var defaultConfig = {
            langType: 'zh-CN',
            uploadJson: rootUrl + '/' + roleName + '/system/Upload/editor',
            //allowFileManager : true,
            filterMode: false,
            height: 550,
            width: '100%',
            tools: 'default'
            //afterBlur: function () { this.sync();}
        };
        config = $.extend(defaultConfig, config, $(this).data());
        if (config.tools == 'image') {
            config.items = [
                'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
                'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
                'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
                'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
                'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
                'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiupload',  'table', 'hr', 'pagebreak',
                'link', 'unlink', '|', 'xiumi', 'remoteimg', '|', 'about'
            ];
        }
        Do('editor', function () {
            var name = $($el).attr("name") + 'DuxEditor';
            var editor = KindEditor.create($($el), config);
            if (window['duxEditor'] == undefined) {
                window['duxEditor'] = [];
            }
            window['duxEditor'][name] = editor;
        });
    };

    /**
     * tag输入组件
     */
    owner.tags = function ($el, config) {
        var defaultConfig = {};
        config = $.extend(defaultConfig, config);
        Do('tags', function () {
            $($el).tagsInput(config);
        });
    };

    /**
     * 下拉选择
     */
    owner.select = function ($el, config) {
        var defaultConfig = {
            language: "zh-CN"
        };
        config = $.extend(defaultConfig, config);
        Do('select2', function () {
            $.fn.select2.defaults.set("theme", "uikit");
            if (config.user) {
                var ajaxConfig = {
                    ajax: {
                        url: config.url,
                        dataType: 'json',
                        delay: 250,
                        data: function (params) {
                            return {
                                q: params.term,
                                page: params.page
                            };
                        },
                        processResults: function (data, params) {
                            params.page = params.page || 1;

                            return {
                                results: data.items,
                                pagination: {
                                    more: (params.page * 30) < data.total_count
                                }
                            };
                        },
                        cache: false
                    },
                    escapeMarkup: function (markup) {
                        return markup;
                    },
                    minimumInputLength: 2,
                    templateResult: function (repo) {
                        if (repo.loading) {
                            return repo.value || repo.text;
                        }
                        var markup = "<div class='select2-result-repository uk-clearfix'>" +
                            "<div class='select2-result-repository__meta'>" +
                            "<div class='select2-result-repository__title'>" + repo.text + "</div>";
                        markup += "<div class='select2-result-repository__description'>" + repo.desc ? repo.desc : '' + "</div>";
                        markup += "</div></div>";
                        return markup;
                    },
                    templateSelection: function (repo) {
                        if (typeof config.callback === 'function') {
                            config.callback(repo);
                        }
                        if (typeof config.callback === 'string' && config.callback) {
                            window[config.callback](repo);
                        }
                        return repo.text;
                    }
                };


                config = $.extend(config, ajaxConfig);
            }
            $($el).select2(config);
        });
    };

    /**
     * 地图组件
     * @param $el
     * @param config
     */
    owner.map = function ($el, config) {
        var defaultConfig = {};
        config = $.extend(defaultConfig, config);
        var id = $($el).data('id');
        $($el).on('click', function () {
            layer.open({
                title: '地图选择',
                type: 2,
                id: 'dialog-' + id,
                area: ['500px', '400px'],
                fix: false,
                btn: ['确定', '取消'],
                content: rootUrl + '/' + roleName + '/site/FormField/map?id=' + id,
                yes: function (index, layero) {
                    var iframe = $(layero).find("iframe");
                    iframe[0].contentWindow.getMap(id);
                    dialog.close();
                }
            });
        });

    };

    /**
     * 上传
     * @param $el
     * @param config
     */
    owner.upload = function ($el, config) {
        var defaultConfig = {
            url: rootUrl + '/' + roleName + '/system/Upload/index',
            type: '*',
            size: 0,
            num: 0,
            multi: true,
            resize: {},
            target: '',
            preview: '',
            callback: '',
            relative: 'false',
            progress: ''
        };
        config = $.extend(defaultConfig, config);
        var uploader;
        Do('upload', function () {
            uploader = new plupload.Uploader({
                runtimes: 'html5,html4',
                browse_button: $($el).get(0),
                url: config.url,
                filters: {
                    mime_types: [{
                        title: "指定文件",
                        extensions: config.type
                    }]
                },
                max_file_size: config.size,
                multipart: config.multi,
                resize: config.resize,
                init: {
                    PostInit: function () {
                        //初始化

                    },
                    FilesAdded: function (up, files) {
                        if (config.num > 0) {
                            if (up.files.length > config.num) {
                                dialog.msg('超过上传数量限制!');
                                uploader.removeFile(files);
                                return;
                            }
                        }
                        //添加文件
                        $($el).attr('disabled', true).append(' <span class="prs">[<strong>0%</strong>]</span>');
                        uploader.start();
                    },
                    UploadProgress: function (up, file) {
                        //上传进度
                        $($el).find('span').text(file.percent + '%');
                        if (typeof config.progress === 'string' && config.progress) {
                            window[config.progress].call($el, file.percent);
                        }

                    },
                    FileUploaded: function (up, file, response) {
                        //文件上传完毕
                        var data = JSON.parse(response.response);
                        if (!data.status) {
                            dialog.msg(data.info);
                            return;
                        }
                        //赋值地址
                        if (config.target) {
                            $(config.target).val(data.data.url);
                        }
                        //图片预览
                        if (config.preview) {
                            $(config.preview).attr('src', data.data.url);
                        }
                        //设置回调
                        if (typeof config.callback === 'function') {
                            config.callback.call($el, data.data);
                        }
                        if (typeof config.callback === 'string' && config.callback) {
                            window[config.callback].call($el, data.data);
                        }
                    },
                    Error: function (up, err) {
                        //错误信息
                        $($el).attr('disabled', false).find('span').remove();
                        dialog.msg(err.message);
                    },
                    UploadComplete: function (up, num) {
                        //队列上传完毕
                        $($el).attr('disabled', false).find('span').remove();
                    }
                }
            });
            uploader.init();
        });
        return uploader;
    };
    /**
     * 组图
     * @param $el
     * @param config
     */
    owner.images = function ($el, config) {
        var defaultConfig = {
            imgWarp: '',
            imgName: '',
            imgList: {},
            imgField: '',
            tplEl: ''
        };
        config = $.extend(defaultConfig, config);
        Do('tpl', function () {

            var imgFields = [];

            if (config.imgField) {
                imgFields = config.imgField.split(",");
            }
            var tpl = '<li class="dux-images-item">' +
                '<img src="{{ d.data.url }}">' +
                '<div class="info">' +
                '<span class="title">{{ d.data.title }}</span>' +
                '<a class="del">删除</a>' +
                '</div>' +
                '<input type="hidden" name="{{ d.name }}[url][]" value="{{ d.data.url }}">' +
                '<input type="hidden" name="{{ d.name }}[title][]" value="{{ d.data.title }}">';
            if (imgFields.length > 0) {
                $.each(imgFields, function (k, v) {
                    tpl += '<input type="hidden" name="{{ d.name }}[' + v + '][]" value="{{ d.data.' + v + ' }}">';
                });
            }

            if (config.tplEl) {
                tpl = $(config.tplEl).html();
            }

            tpl += '</li>';
            $(config.imgWarp).on('click', '.del', function () {
                $(this).parents('li.dux-images-item').remove();
            });
            owner.upload($el, $.extend(config, {
                callback: function (data) {
                    laytpl(tpl).render({
                        name: config.imgName,
                        data: data
                    }, function (html) {
                        $(config.imgWarp).append(html);
                    });
                }
            }));
            if (config.imgList) {
                $.each(config.imgList, function (index, item) {
                    laytpl(tpl).render({
                        name: config.imgName,
                        data: item
                    }, function (html) {
                        $(config.imgWarp).append(html);
                    });
                });
            }

        });
    };

    /**
     * 图片预览
     * @param $el
     * @param config
     */
    owner.imgShow = function ($el, config) {
        var defaultConfig = {
            target: ''
        };
        config = $.extend(defaultConfig, config);
        $($el).on('click', function () {
            var image = $(config.target).val();
            if (!image) {
                dialog.msg('请先上传图片!');
                return;
            }
            window.open(image);
        });
    };

    /**
     * 多文件
     * @param $el
     * @param config
     */
    owner.files = function ($el, config) {
        var defaultConfig = {
            fileWarp: '',
            fileName: '',
            fileList: {}
        };
        config = $.extend(defaultConfig, config);
        Do('tpl', function () {
            var tpl = '<li>' +
                '<span class="title"><input type="text" name="{{ d.name }}[title][]" value="{{ d.data.title }}">.{{ d.data.ext }} ({{ (d.data.size/1024).toFixed(2) }}kb)</span> ' +
                '<a class="del">删除</a>' +
                '<input type="hidden" name="{{ d.name }}[url][]" value="{{ d.data.url }}">' +
                '<input type="hidden" name="{{ d.name }}[ext][]" value="{{ d.data.ext }}">' +
                '<input type="hidden" name="{{ d.name }}[size][]" value="{{ d.data.size }}">' +
                '</li>';
            $(config.fileWarp).on('click', '.del', function () {
                $(this).parents('li').remove();
            });
            owner.upload($el, $.extend(config, {
                callback: function (data) {
                    laytpl(tpl).render({
                        name: config.fileName,
                        data: data
                    }, function (html) {
                        $(config.fileWarp).append(html);
                    });
                }
            }));
            if (config.fileList) {
                $.each(config.fileList, function (index, item) {
                    laytpl(tpl).render({
                        name: config.fileName,
                        data: item
                    }, function (html) {
                        $(config.fileWarp).append(html);
                    });
                });
            }

        });
    };

    /**
     * 列表刷新
     */
    owner.refresh = function ($el, config) {
        var defaultConfig = {
            type: 'select',
            target: ''
        };
        config = $.extend(defaultConfig, config);
        $($el).on('click', function () {
            app.ajax({
                url: config.url,
                type: 'post',
                data: config.params,
                success: function (msg, url) {
                    var callback = config.callback;
                    if (callback != undefined && callback != '') {
                        window[callback](msg, url);
                    } else {
                        var html = '';
                        if (config.type == 'select') {
                            if (msg.length < 1) {
                                html = '<option value="0">' + config.tip + '</option>';
                            } else {
                                for (var i in msg) {
                                    html += '<option value="' + msg[i].value + '">' + msg[i].name + '</option>';
                                }
                            }
                        }
                        $(config.target).html(html);
                    }
                },
                error: function (msg, url) {
                    app.error(msg, url);
                }
            });
        });
    };

    owner.color = function ($el, config) {
        var defaultConfig = {};
        config = $.extend(defaultConfig, config);
        Do('color', function () {
            $($el).colorpicker(config);
        });
    };


}(jQuery, window.form = {}));


(function ($, owner) {

    /**
     * TAB组件
     * @param $el
     * @param config
     */
    owner.tab = function ($el, config) {
        var defaultConfig = {
            active: "active"
        };
        config = $.extend(defaultConfig, config);
        var els = [];
        $($el).find('a').each(function () {
            els.push($(this).data('el'));
        });
        var switchTab = function (obj) {
            $(els.join(',')).hide();
            $($(obj).data('el')).show();
        };
        $($el).on('click', 'a', function () {
            $($el).find('li').removeClass(config.active);
            $(this).parents('li').addClass(config.active);
            switchTab(this);
        });
        switchTab($($el).find('.' + config.active).find('a'));
    };

    owner.filter = function ($el, config) {
        var defaultConfig = {
            active: "active"
        };
        config = $.extend(defaultConfig, config);
        $($el).find('[data-link]').on('click', function () {
            $(this).parent().addClass('active');
            if ($($el).find('[data-sub]').is(":hidden")) {
                $($el).find('[data-sub]').hide();
                $(this).parent().find('[data-sub]').show();
            } else {
                $($el).find('[data-sub]').hide();
            }
        });
    };

    /**
     * 分享组件
     * @param $el
     * @param config
     */
    owner.share = function ($el, config) {
        var defaultConfig = {
            disabled: ['google', 'facebook', 'twitter', 'diandian', 'tencent']
        };
        config = $.extend(defaultConfig, config);
        Do('share', function () {
            $($el).share(config);
        });
    };

    /**
     * 步骤
     * @param $el
     * @param config
     */
    owner.step = function ($el, config) {
        var defaultConfig = {};
        config = $.extend(defaultConfig, config);
        $($el).find('.active').prevAll().addClass("active");
    };

    /**
     * 地图
     */
    owner.tmap = function ($el, config) {
        var defaultConfig = {
            lat: null,
            lng: null,
            address: null,
            callback: ''
        };
        config = $.extend(defaultConfig, config);
        window['tmapInit'] = function () {
            var position = new qq.maps.LatLng(config.lat ? config.lat : 39.916527, config.lng ? config.lng : 116.397128);
            var myOptions = {
                center: position,
                zoom: 14,

                mapTypeId: qq.maps.MapTypeId.ROADMAP
            };
            var id = $($el).attr('id');
            var map = new qq.maps.Map($($el)[0], myOptions);

            if (config.address) {
                var callbacks = {
                    complete: function (result) {
                        position = result.detail.location;
                        map.setCenter(position);
                        new qq.maps.Marker({
                            map: map,
                            position: position
                        });
                    },
                };
                geocoder = new qq.maps.Geocoder(callbacks);
                geocoder.getLocation(config.address);
            } else {
                if (config.lat && config.lng) {
                    new qq.maps.Marker({
                        map: map,
                        position: position
                    });
                }
            }

            if (config.callback != undefined && config.callback != '') {
                window[config.callback](map, position, $el);
            }
        };
        Do('tmap');
    };

    owner.qrcode = function ($el, config) {
        var defaultConfig = {};
        config = $.extend(defaultConfig, config);
        Do('qrcode', function () {
            $($el).qrcode(config);
        });
    };

    owner.listAction = function ($el, config) {
        var defaultConfig = {
            width: 70
        };
        config = $.extend(defaultConfig, config);

        $($el).unbind('click').unbind('touchstart').unbind('touchmove').unbind('touchend').on({
            'touchmove': function (event) {
                if (event.originalEvent.targetTouches.length == 1) {
                    var touch = event.originalEvent.targetTouches[0],
                        leftX;
                    leftX = touch.pageX - this.startX;
                    this.isMove = true;
                    this.leftX = leftX;
                    this.style.webkitTransition = "-webkit-transform 0s ease";
                    if (leftX < 0) {
                        this.re = 'l';
                        if (leftX < -config.width) {
                            leftX = -config.width;
                        }
                        if (this.stats == 'r') {
                            this.style.webkitTransform = 'translateX(' + leftX + 'px)';
                        }
                    } else {
                        this.re = 'r';
                        if (leftX > config.width) {
                            leftX = config.width;
                        }
                        if (this.stats == 'l') {
                            this.style.webkitTransform = 'translateX(' + (leftX - config.width) + 'px)';
                        }
                    }
                    if (Math.abs(leftX) > 10) {
                        return false;
                    } else {
                        this.style.webkitTransform = 'translateX(0px)';
                    }
                }
            },
            'touchstart': function (event) {
                if (event.originalEvent.targetTouches.length == 1) {
                    if (!this.stats) {
                        this.stats = 'r';
                    }
                    this.startTime = new Date().getTime();
                    var touch = event.originalEvent.targetTouches[0];
                    this.startX = touch.pageX;
                    this.isMove = false;
                }
            },
            'touchend': function (event) {
                this.style.webkitTransition = "-webkit-transform 0.5s ease";
                if (this.re == 'r') {
                    this.style.webkitTransform = 'translateX(0px)';
                    this.stats = 'r';
                } else {
                    if (this.leftX > -config.width / 2) {
                        this.style.webkitTransform = 'translateX(0px)';
                        this.stats = 'r';
                    } else {
                        this.style.webkitTransform = 'translateX(-' + config.width + 'px)';
                        this.stats = 'l';
                    }
                }
            }
        }, '[data-item]');
    };


    owner.more = function ($el, config) {
        var defaultConfig = {};
        config = $.extend(defaultConfig, config);
        $($el).on('click', function () {
            var $content = $('#' + config['id']),
                status = $content.data('status'),
                height = config['height'];
            if (status) {
                $content.css('max-height', height).css('overflow', 'hidden');
                $content.data('status', 0);
            } else {
                $content.css('max-height', 'none').css('overflow', 'auto');
                $content.data('status', 1);
            }
        });
    };

    owner.dialog = function ($el, config) {
        var defaultConfig = {};
        config = $.extend(defaultConfig, config);
        $('body').addClass('uk-dimmer-active');
        $($el).addClass('dux-dialog-active');
        $($el).on('close', function () {
            $($el).removeClass('dux-dialog-active');
            $('body').removeClass('uk-dimmer-active');
            if (typeof config.callback === 'function') {
                config.callback.apply($el);
            }
        });
        $($el).find('[data-close]').on('click', function () {
            owner.dialog.close($el);
        });
    };

    owner.dialog.close = function ($el) {
        $($el).trigger('close');
    };

    //弹出窗口
    owner.popup = function ($el, config) {
        var defaultConfig = {};
        config = $.extend(defaultConfig, config);
        $($el).addClass('dux-popup-active');
        $($el).append('<div class="dux-popup-mask"></div>');
        $('body').css("overflow","hidden");
        //反射条件
        $($el).on('close', function () {
            $($el).removeClass('dux-popup-active');
            $($el).find('.dux-popup-mask').remove();
            $('body').css("overflow","auto");
            if (typeof config.callback === 'function') {
                config.callback.apply($el);
            }
        });
        $($el).find('[data-close]').on('click', function () {
            owner.popup.close($el);
        });
        $($el).find('.dux-popup-mask').on('click', function() {
            owner.popup.close($el);
        });
    };
    owner.popupOpen = function ($el, config) {
        var defaultConfig = {};
        config = $.extend(defaultConfig, config);
        $($el).on('click', function () {
            owner.popup(config.el);
        });
    };

    owner.popup.close = function ($el) {
        $($el).trigger('close');
    }

}(jQuery, window.show = {}));

/**
 * 通知组件
 */
(function ($, owner) {
    owner.success = function (config) {
        var defaultConfig = {
            content: "处理成功",
            time: 6
        };
        config = $.extend(defaultConfig, config, {
            status: 'success'
        });
        owner.show(config);
    };
    owner.warning = function (config) {
        var defaultConfig = {
            content: "处理中断",
            time: 6
        };
        config = $.extend(defaultConfig, config, {
            status: 'warning'
        });
        owner.show(config);
    };
    owner.error = function (config) {
        var defaultConfig = {
            content: "处理失败",
            time: 6

        };
        config = $.extend(defaultConfig, config, {
            status: 'error'
        });
        owner.show(config);
    };
    owner.show = function (config) {
        var status = {
            success: ['success', '#27ae60'],
            warning: ['warning', '#e0690c'],
            error: ['danger', '#dd514c']
        };
        UIkit.notification({
            message: config.content,
            status: status[config.status][0],
            timeout: config.time * 1000
        });
    };
}(jQuery, window.notify = {}));

(function ($, owner) {

    /**
     * ajax加载更多
     */
    owner.ajaxPage = function ($el, config) {
        Do('tpl', function () {
            var defaultConfig = {
                page: 1,
                url: '',
                list: '',
                tpl: '',
                label: 'dataList'
            };
            config = $.extend(defaultConfig, config);

            var page = config.page;
            var initLoad = true; //默认加载
            var initStatus = true; //数据状态
            var loadLock = false; //加载锁定
            var callback = $($el).data('callback');
            var error = $($el).data('error');

            //加载定义
            var loading = function (status) {
                var html = '';
                if (!status) {
                    //加载提示
                    html = '<div>上拉加载更多</div>';
                }
                if (status == 1) {
                    //正在加载
                    html = '<div><span class="loading"></span> 正在加载中...</div>';

                }
                if (status == 2) {
                    //没有更多
                    html = '<div>没有更多</div>';
                }
                $(config.list).next('[data-dux-more]').html(html);
            }
            //默认布局
            $(config.list).after('<div class="dux-ajax-more" data-dux-more></div>');
            loading(1);

            var lockLoad = function () {
                //加载数据中
                loading(1);
                loadLock = true;
                initStatus = true;
            }

            var unLockLoad = function () {
                loading(0);
                loadLock = false;
                initStatus = true;
            }

            var overLoad = function () {
                loading(2);
                loadLock = false;
                initStatus = false;
            }

            //存储历史加载
            $(config.list).on('click', function () {
                var html = $(config.list).html();
                var data = {};
                data.page = page;
                data.html = html;
                data.pos = function () {
                    var scrollTop = 0;
                    if (document.documentElement && document.documentElement.scrollTop) {
                        scrollTop = document.documentElement.scrollTop;
                    } else if (document.body) {
                        scrollTop = document.body.scrollTop;
                    }
                    return scrollTop;
                }();
                history.replaceState(data, '', document.location.href);
            });

            //恢复历史加载数据
            if (!!(window.history.state && window.history.state.html)) {
                initLoad = false;
                page = window.history.state.page;
                $(config.list).html(window.history.state.html);
                history.replaceState({}, '', document.location.href);
                setTimeout(window.scroll(0, window.history.state.pos || 0), 200);
                loading(0);
            }

            var loadData = function () {
                lockLoad();
                app.ajax({
                    type: 'GET',
                    url: config.url,
                    async: false,
                    data: {
                        'page': page
                    },
                    success: function (info) {
                        setTimeout(function () {
                            var tpl = $(config.tpl).html();
                            laytpl(tpl).render(info.data, function (html) {
                                page++;
                                $(config.list).append(html);
                            });
                            if (callback != undefined && callback != '') {
                                window[callback](info);
                            }
                            unLockLoad();
                        }, 1000);

                    },
                    error: function (msg, url) {
                        setTimeout(function () {
                            if (error != undefined && error != '') {
                                window[error](msg, url, page);
                            }
                            overLoad();
                        }, 1000);
                    }
                });
            }

            var throttle = function (func, delay) {
                var timer = null;
                var startTime = Date.now();
                return function () {
                    var curTime = Date.now();
                    var remaining = delay - (curTime - startTime);
                    var context = this;
                    var args = arguments;
                    clearTimeout(timer);
                    if (remaining <= 0) {
                        func.apply(context, args);
                        startTime = Date.now();
                    } else {
                        timer = setTimeout(func, remaining);
                    }
                }
            }

            $(window).scroll(throttle(function () {
                var scrollTop = $(this).scrollTop();
                var scrollHeight = $(document).height();
                var clientHeight = $(this).height();
                if (scrollTop + clientHeight >= scrollHeight - 50) {
                    if (!initStatus || loadLock) {
                        return false;
                    }
                    loadData();
                }
            }, 500));

            $(document).ready(function () {
                if (!initLoad) {
                    initLoad = true;
                    return false;
                }
                loadData();
            });
        });
    };
    /**
     * 超链接访问
     */
    owner.ajaxLink = function ($el, config) {
        Do('base', function () {
            var defaultConfig = {
                callback: ''
            };
            config = $.extend(defaultConfig, config);
            $($el).click(function () {
                var data = $(this).data();
                var datas = data.data ? data.data : {};
                var field = data.field ? data.field : '';
                var fieldArray = new Array();
                if (data.field) {
                    fieldArray = field.split(',');
                    for (var i = 0; i < fieldArray.length; i++) {
                        datas[fieldArray[i]] = $('#' + fieldArray[i]).val();
                    }
                }
                app.ajax({
                    url: data.url,
                    type: 'post',
                    data: datas,
                    loading: true,
                    success: function (msg) {
                        app.success(msg);
                        //设置回调
                        if (typeof config.callback === 'function') {
                            config.callback(data.data);
                        }
                        if (typeof config.callback === 'string' && config.callback) {
                            window[config.callback].apply($el, data.data);
                        }
                    },
                    error: function (msg) {
                        app.error(msg);
                    }
                });
            });
        });
    };

    var countdown = 60;
    /**
     * 验证码倒计时
     */
    owner.getCode = function ($el) {
        owner.ajaxLink($el, {
            callback: function () {
                owner._codeTime($el);
            }
        });
    };
    owner._codeTime = function (val) {
        if (countdown == 0) {
            countdown = 60;
            $(val).text('获取验证码').attr('disabled', false);
        } else {
            countdown--;
            $(val).text(countdown + '秒后获取').attr('disabled', true);

            setTimeout(function () {
                owner._codeTime(val)
            }, 1000);
        }
    }

}(jQuery, window.page = {}));


/**
 * 常用方法
 */
(function ($, owner) {
    /**
     * 调试方法
     * @param msg
     */
    owner.debug = function (msg) {
        if (!debug) {
            return false;
        }
        if (typeof (console) != 'undefined') {
            console.log(msg);
        }
    };
    /**
     * AJAX请求
     * @param config
     */
    owner.ajax = function (config) {
        var defaultConfig = {
            async: true
        };
        config = $.extend(defaultConfig, config);
        if (config.loading) {
            dialog.loading();
        }
        var profiler = function (data) {
            if (!debug) {
                return false;
            }

            if (!data) {
                return false;
            }
        };
        $.ajax({
            url: config.url,
            type: config.type,
            data: config.data,
            async: config.async,
            dataType: 'json',
            beforeSend: function (request) {
                if (window.source) {
                    request.setRequestHeader("from", window.source);
                }
            },
            success: function (json) {
                if (config.loading) {
                    dialog.loading('', false);
                }
                if (typeof config.success == 'function') {
                    config.success(json.message, json.url);
                }
                profiler(json);
            },
            error: function (e) {
                if (config.loading) {
                    dialog.loading('', false);
                }
                try {
                    var json = eval('(' + e.responseText + ')');
                    var msg = json.message;
                    var url = json.url;
                } catch (e) {
                    var msg = null;
                    var url = null;
                }
                profiler(json);
                if (msg == '' || msg == null) {
                    msg = '数据请求失败，请刷新后再试！';
                }

                if (e.status == 404) {
                    app.error('请求操作不存在!');
                    return;
                }
                if (e.status == 401) {
                    if (typeof config.login == 'function') {
                        config.login(msg);
                        return;
                    } else {
                        app.error(msg, url);
                        return;
                    }
                }
                if (e.status == 501) {
                    dialog.confirm({
                        title: msg,
                        callback: [function () {
                            window.postMessage('{"event":"jump", "url":"' + url + '"}');
                            dialog.close();
                        }]
                    });
                    return;
                }
                if (typeof config.error == 'function') {
                    config.error(msg, url);
                    return;
                }
                app.error(msg, url);
            }
        });
    };
    /**
     * 成功提示
     * @param msg
     * @param url
     */
    owner.success = function (msg, url) {
        if (url) {
            window.location.href = url;
        } else {
            dialog.msg(msg);
        }
    };
    /**
     * 失败提示
     * @param msg
     * @param url
     */
    owner.error = function (msg, url) {
        if (url) {
            dialog.confirm({
                title: msg,
                callback: [function () {
                    window.location.href = url;
                }]
            });
        } else {
            dialog.msg(msg);
            return false;
        }
    };

    /**
     * 移动端检测
     * @returns {boolean}
     */
    owner.mobile = function () {
        var check = false;
        if (navigator.userAgent.match(/(mobile|iPhone|iPod|Android|ios)/i)) {
            check = true;
        } else if (screen.width <= 1024) {
            check = true;
        }
        return check;
    };

    /**
     * 复制内容
     * @param $el
     */
    owner.copy = function ($el) {
        Do('copy', function () {
            var client = new ZeroClipboard($el);
            client.on("aftercopy", function (event) {
                dialog.msg('复制成功，请直接粘贴使用！');
            });

        });
    };

    /**
     * 加载JS
     * @param url
     * @param callback
     */
    owner.loadJs = function (url, callback) {
        var head = document.getElementsByTagName('head')[0];
        var script = document.createElement('script');
        script.type = 'text/javascript';
        script.src = url;
        if (typeof (callback) == 'function') {
            script.onload = script.onreadystatechange = function () {
                if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
                    callback();
                    script.onload = script.onreadystatechange = null;
                }
            };
        }
        head.appendChild(script);
    };

    /**
     * 唯一ID生成
     * @returns {string}
     */
    owner.guid = function () {
        function S4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }

        return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    };

    owner.datetime = function (unix) {
        var now = new Date(parseInt(unix) * 1000);
        return now.toLocaleString().replace(/年|月/g, "-").replace(/日/g, " ");
    };

    owner.date = function (format, timestamp) {
        var a, jsdate = ((timestamp) ? new Date(timestamp * 1000) : new Date());
        var pad = function (n, c) {
            if ((n = n + "").length < c) {
                return new Array(++c - n.length).join("0") + n;
            } else {
                return n;
            }
        };
        var txt_weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
        var txt_ordin = {
            1: "st",
            2: "nd",
            3: "rd",
            21: "st",
            22: "nd",
            23: "rd",
            31: "st"
        };
        var txt_months = ["", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
        var f = {
            // Day
            d: function () {
                return pad(f.j(), 2)
            },
            D: function () {
                return f.l().substr(0, 3)
            },
            j: function () {
                return jsdate.getDate()
            },
            l: function () {
                return txt_weekdays[f.w()]
            },
            N: function () {
                return f.w() + 1
            },
            S: function () {
                return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th'
            },
            w: function () {
                return jsdate.getDay()
            },
            z: function () {
                return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0
            },

            // Week
            W: function () {
                var a = f.z(),
                    b = 364 + f.L() - a;
                var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;
                if (b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b) {
                    return 1;
                } else {
                    if (a <= 2 && nd >= 4 && a >= (6 - nd)) {
                        nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
                        return date("W", Math.round(nd2.getTime() / 1000));
                    } else {
                        return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
                    }
                }
            },

            // Month
            F: function () {
                return txt_months[f.n()]
            },
            m: function () {
                return pad(f.n(), 2)
            },
            M: function () {
                return f.F().substr(0, 3)
            },
            n: function () {
                return jsdate.getMonth() + 1
            },
            t: function () {
                var n;
                if ((n = jsdate.getMonth() + 1) == 2) {
                    return 28 + f.L();
                } else {
                    if (n & 1 && n < 8 || !(n & 1) && n > 7) {
                        return 31;
                    } else {
                        return 30;
                    }
                }
            },

            // Year
            L: function () {
                var y = f.Y();
                return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0
            },
            Y: function () {
                return jsdate.getFullYear()
            },
            y: function () {
                return (jsdate.getFullYear() + "").slice(2)
            },

            // Time
            a: function () {
                return jsdate.getHours() > 11 ? "pm" : "am"
            },
            A: function () {
                return f.a().toUpperCase()
            },
            B: function () {
                // peter paul koch:
                var off = (jsdate.getTimezoneOffset() + 60) * 60;
                var theSeconds = (jsdate.getHours() * 3600) + (jsdate.getMinutes() * 60) + jsdate.getSeconds() + off;
                var beat = Math.floor(theSeconds / 86.4);
                if (beat > 1000) beat -= 1000;
                if (beat < 0) beat += 1000;
                if ((String(beat)).length == 1) beat = "00" + beat;
                if ((String(beat)).length == 2) beat = "0" + beat;
                return beat;
            },
            g: function () {
                return jsdate.getHours() % 12 || 12
            },
            G: function () {
                return jsdate.getHours()
            },
            h: function () {
                return pad(f.g(), 2)
            },
            H: function () {
                return pad(jsdate.getHours(), 2)
            },
            i: function () {
                return pad(jsdate.getMinutes(), 2)
            },
            s: function () {
                return pad(jsdate.getSeconds(), 2)
            },
            // Timezone
            O: function () {
                var t = pad(Math.abs(jsdate.getTimezoneOffset() / 60 * 100), 4);
                if (jsdate.getTimezoneOffset() > 0) t = "-" + t;
                else t = "+" + t;
                return t;
            },
            P: function () {
                var O = f.O();
                return (O.substr(0, 3) + ":" + O.substr(3, 2))
            },
            // Full Date/Time
            c: function () {
                return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P()
            },
            U: function () {
                return Math.round(jsdate.getTime() / 1000)
            }
        };

        return format.replace(/[\\]?([a-zA-Z])/g, function (t, s) {
            var ret = '';
            if (t != s) {
                ret = s;
            } else if (f[s]) {
                ret = f[s]();
            } else {
                ret = s;
            }
            return ret;
        });
    };
}(jQuery, window.app = {}));